package com.sc.VenusQueryBeta.ui.activites.login;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.dou361.dialogui.DialogUIUtils;
import com.dou361.dialogui.listener.DialogUIListener;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import com.hengjun.kingstar.sdk.base.BasePresenter;
import com.hengjun.kingstar.sdk.base.activity.BaseMVPCompatActivity;
import com.hengjun.kingstar.sdk.utils.LogUtils;
import com.hengjun.kingstar.sdk.utils.SpUtils;
import com.hengjun.kingstar.sdk.utils.ToastUtils;
import com.hengjun.kingstar.sdk.widgets.ClearEditText;
import com.hengjun.kingstar.sdk.widgets.CountDownButton;
import com.hengjun.kingstar.sdk.widgets.DeviceIDUtil;
import com.hengjun.kingstar.sdk.widgets.TipHelper;
import com.sc.VenusQueryBeta.R;
import com.sc.VenusQueryBeta.constant.Constants;
import com.sc.VenusQueryBeta.contract.login.RegisterContract;
import com.sc.VenusQueryBeta.global.MyApplication;
import com.sc.VenusQueryBeta.model.bean.login.RegisterVerticationBean;
import com.sc.VenusQueryBeta.presenter.login.RegisterPresenter;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

public class RegisterActivity extends BaseMVPCompatActivity<RegisterContract.RegisterPresenter> implements RegisterContract.IRegisterView {

    @BindView(R.id.tv_country_name_register)
    TextView tvCountryNameRegister;
    @BindView(R.id.tv_number)
    TextView tvNumber;
    @BindView(R.id.phone_register)
    ClearEditText phoneRegister;
    @BindView(R.id.register_number)
    CountDownButton loginGetNumber;
    @BindView(R.id.get_number)
    ClearEditText getNumber;
    @BindView(R.id.btn_register_next)
    Button btnRegisterNext;
    @BindView(R.id.sv_main)
    ScrollView svMain;

    @BindView(R.id.root_view)
    LinearLayout rootView;
    @BindView(R.id.about_register_back)
    ImageButton aboutRegisterBack;

    private PopupWindow popupWindow;
    private TextView countryDalu;
    private TextView countryMacao;
    private TextView countryHk;
    private TextView countryTw;
    private TextView countryOther;
    private String s;
    private Drawable img;
    private String deviceUid;//设备id
    private String countryCode = "1";//澳门
    private PhoneNumberUtil phoneUtil;
    private Phonenumber.PhoneNumber parse;


    @Override
    protected void initView(Bundle savedInstanceState) {

        //initMoveKeyBoard();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_register;
    }

    @SuppressLint("WrongConstant")
    private void inputOtherPwdWindow() {
        final View contentView = LayoutInflater.from(this).inflate(R.layout.country_chooise, null);
        countryDalu = contentView.findViewById(R.id.country_dalu);
        countryMacao = contentView.findViewById(R.id.country_macao);
        countryHk = contentView.findViewById(R.id.country_hk);
        countryTw = contentView.findViewById(R.id.country_tw);
        countryOther = contentView.findViewById(R.id.country_other);

        if (popupWindow == null) {
            popupWindow = new PopupWindow(contentView, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, true);
        }
        popupWindow.setTouchable(true);
        popupWindow.setFocusable(true); //设置点击menu以外其他地方以及返回键退出
        popupWindow.setOutsideTouchable(true);   //设置触摸外面时消失
        popupWindow.getContentView().setFocusableInTouchMode(true);
        popupWindow.getContentView().setFocusable(true);
        // 设置弹出窗体的背景
        popupWindow.setBackgroundDrawable(new BitmapDrawable(MyApplication.app.getResources(), (Bitmap) null));
        ColorDrawable cd = new ColorDrawable();
        popupWindow.setBackgroundDrawable(cd);
        //这句话，让pop覆盖在输入法上面
        popupWindow.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
        popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);

        // 5 在底部显示
        popupWindow.showAtLocation(contentView.findViewById(R.id.country_register_chooise),
                Gravity.CENTER, 0, 0);
        initLilstener();

    }

    /**
     * 監聽pup
     *
     * @param
     */
    private void initLilstener() {
        /**
         * 點擊大陸
         */
        countryDalu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                countryCode = "0";
                s = countryDalu.getText().toString();
                tvCountryNameRegister.setText(s);
                tvNumber.setText("+86");
                img = getResources().getDrawable(R.drawable.cn2x);
                img.setBounds(0, 0, img.getMinimumWidth(), img.getMinimumHeight()); //设置边界
                tvCountryNameRegister.setCompoundDrawables(img, null, null, null);
                popupWindow.dismiss();
            }
        });
        /**
         * 點擊澳門
         */
        countryMacao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                countryCode = "1";
                s = countryMacao.getText().toString();
                tvCountryNameRegister.setText(s);
                tvNumber.setText("+853");
                img = getResources().getDrawable(R.drawable.mo2x);
                img.setBounds(0, 0, img.getMinimumWidth(), img.getMinimumHeight()); //设置边界
                tvCountryNameRegister.setCompoundDrawables(img, null, null, null);
                popupWindow.dismiss();
            }
        });
        /**
         * 點擊香港
         */
        countryHk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                countryCode = "2";
                s = countryHk.getText().toString();
                tvCountryNameRegister.setText(s);
                tvNumber.setText("+852");
                img = getResources().getDrawable(R.drawable.hk2x);
                img.setBounds(0, 0, img.getMinimumWidth(), img.getMinimumHeight()); //设置边界
                tvCountryNameRegister.setCompoundDrawables(img, null, null, null);
                popupWindow.dismiss();
            }
        });
        /**
         * 點擊台灣
         */
        countryTw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                countryCode = "3";
                s = countryTw.getText().toString();
                tvCountryNameRegister.setText(s);
                tvNumber.setText("+886");
                img = getResources().getDrawable(R.drawable.img_tw2x);
                img.setBounds(0, 0, img.getMinimumWidth(), img.getMinimumHeight()); //设置边界
                tvCountryNameRegister.setCompoundDrawables(img, null, null, null);
                popupWindow.dismiss();
            }
        });
        /**
         * 點擊其他
         */
        countryOther.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                countryCode = "4";
                s = countryOther.getText().toString();
                tvCountryNameRegister.setText(s);
                tvNumber.setText("");
                img = getResources().getDrawable(R.drawable.other2x);
                img.setBounds(0, 0, img.getMinimumWidth(), img.getMinimumHeight()); //设置边界
                tvCountryNameRegister.setCompoundDrawables(img, null, null, null);
                popupWindow.dismiss();
            }
        });
    }

    @OnClick({R.id.tv_country_name_register, R.id.btn_register_next, R.id.register_number, R.id.about_register_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_country_name_register://打開國家地區號
                inputOtherPwdWindow();
                break;
            case R.id.btn_register_next://下一步
                if (!phoneRegister.getText().toString().trim().equals("") && !getNumber.getText().toString().trim().equals("")) {
                    String ver = SpUtils.getString(MyApplication.app, Constants.VERTIFICATION_CODE, "");
                    //验证码不为空
                    if (!ver.equals("")) {
                        if (getNumber.getText().toString().trim().equals(SpUtils.getString(this, Constants.VERTIFICATION_CODE, ""))) {
                            if (!loginGetNumber.isFinish()) {
                                loginGetNumber.cancel();
                            }
                            startActivity(NextRegistActivity.class);
                            finish();
                        } else {
                            ToastUtils.showToast(R.string.error_vertification_code);
                            getNumber.setHint(R.string.error_vertification_code);
                        }
                    } else {
                        ToastUtils.showToast("验证码已过期,请重新获取");
                        return;
                    }
                } else {
                    ToastUtils.showToast(getString(R.string.empty_number));
                }
                break;
            case R.id.register_number:
                //这里判断是否倒计时结束，避免在倒计时时多次点击导致重复请求接口
                if (loginGetNumber.isFinish()) {//完成才調用
                    if (!phoneRegister.getText().toString().trim().equals("")) {
                        try {
                            LogUtils.e("sasa===121===" + tvNumber.getText().toString().substring(1));
                            parse = phoneUtil.parse(tvNumber.getText().toString() + phoneRegister.getText().toString().trim(), tvNumber.getText().toString().substring(1));//判断号码合法
                            if (phoneUtil.isValidNumber(parse)) {//判断号码合法
                                showProgressDialog("正在獲取...");
                                LogUtils.e("手機號碼=" + tvNumber.getText().toString().trim() + phoneRegister.getText().toString().trim());
                                LogUtils.e("clientUID=" + "meg" + phoneRegister.getText().toString().trim());
                                LogUtils.e("deviceUid=" + deviceUid);
                                if (countryCode.equals("1")) {
                                    mPresenter.getVerticatinCode(("meg" + tvNumber.getText().toString() + phoneRegister.getText().toString().trim()), deviceUid, "android",
                                            (phoneRegister.getText().toString().trim()), countryCode, "0"); //flag=0/1 0就是第一次注册时传
                                } else {
                                    mPresenter.getVerticatinCode(("meg" + tvNumber.getText().toString() + phoneRegister.getText().toString().trim()), deviceUid, "android",
                                            (tvNumber.getText().toString().trim() + phoneRegister.getText().toString().trim()), countryCode, "0"); //flag=0/1 0就是第一次注册时传
                                }

                            } else {
                                Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);//加载动画资源文件
                                loginGetNumber.startAnimation(shake);
                                phoneRegister.startAnimation(shake);
                                TipHelper.Vibrate(this, 100);
                                ToastUtils.showToast("手机号码不合法！");
                            }
                        } catch (NumberParseException e) {
                            e.printStackTrace();
                        }

                    } else {
                        Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);//加载动画资源文件
                        loginGetNumber.startAnimation(shake);
                        phoneRegister.startAnimation(shake);
                        TipHelper.Vibrate(this, 100);
                        ToastUtils.showToast("手机号码不能为空！");
                    }
                } else {
                    ToastUtils.showToast("別著急哦");
                }

                break;
            case R.id.about_register_back:
                finish();
                break;
        }
    }


    @NonNull
    @Override
    public BasePresenter initPresenter() {
        return RegisterPresenter.newInstance();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (!loginGetNumber.isFinish()) {
            loginGetNumber.cancel();
        }
    }

    @Override
    public void showVerticationDataSuccess(RegisterVerticationBean registerVerticationBean) {
        //判斷returncode
        if (registerVerticationBean.getReturnCode() == 202) {
            hideProgressDialog();
            ToastUtils.showToast("賬號已經註冊過了.");
        } else if (registerVerticationBean.getReturnCode() == 203) {
            hideProgressDialog();
            ToastUtils.showToast("賬號不存在");
        } else {
            //发送验证码请求成功后调用
            ToastUtils.showToast("發送成功,請注意查收");
            loginGetNumber.start();
            hideProgressDialog();
            SpUtils.putObject(MyApplication.app, registerVerticationBean);
            SpUtils.putString(MyApplication.app, Constants.VERTIFICATION_CODE, registerVerticationBean.getRandomNum());
            LogUtils.e("getRandomNum=" + registerVerticationBean.getRandomNum());
            LogUtils.e("phone==" + registerVerticationBean.getRegisterSmsnum());
            LogUtils.e("设备参数" + registerVerticationBean.getDeviceUID());
            LogUtils.e("这是注册的传参" + registerVerticationBean.getClientUID() + "  " + registerVerticationBean.getDeviceUID() + "  " + registerVerticationBean.getDeviceType() + "     " +
                    registerVerticationBean.getRegisterSmsnum() + "  " + registerVerticationBean.getAreaCode() + "  ");

            Timer timer = new Timer(true);
            TimerTask task = new TimerTask() {
                @Override
                public void run() {
                    SpUtils.remove(MyApplication.app, Constants.VERTIFICATION_CODE);
                    //  LogUtils.e("zoulezheli==========="+Constants.VERTIFICATION_CODE);
                }
            };
            timer.schedule(task, 600000);

//            Toast.makeText(this,registerVerticationBean.getRandomNum(),Toast.LENGTH_LONG).show();

            DialogUIUtils.showAlert(this, "验证码", registerVerticationBean.getRandomNum(), "", "", "确定", "", true, true, true, new DialogUIListener() {
                @Override
                public void onPositive(CharSequence input1, CharSequence input2) {

                }

                @Override
                public void onNegative(CharSequence input1, CharSequence input2) {

                }
            }).show();
        }
    }

    @Override
    public void showNetworkError() {
        hideProgressDialog();
    }

    @Override
    protected void initData() {
        super.initData();
        phoneUtil = PhoneNumberUtil.getInstance();
        deviceUid = new DeviceIDUtil(mContext).getDeviceUuid().toString().replaceAll("-","");
        LogUtils.e("RegistActivity initData deviceUid="+deviceUid);
    }





}
